import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { User } from '../database/entities/user.entity';
import { UserRole } from '../database/entities/user-role.entity';
import { CreateUserDto, UpdateUserDto, QueryUsersDto } from './dto/users.dto';
import { PaginationUtil } from '../common/utils/pagination.util';
import { PaginationResult } from '../common/dto/pagination.dto';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    @InjectRepository(UserRole)
    private userRoleRepository: Repository<UserRole>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    // 如果有密码，需要进行哈希处理
    if (createUserDto.password) {
      createUserDto.password = await bcrypt.hash(createUserDto.password, 12);
    }
    
    const user = this.usersRepository.create(createUserDto);
    return this.usersRepository.save(user);
  }

  async findAll(query: QueryUsersDto): Promise<PaginationResult<User>> {
    const { username, email, phone, status } = query;
    
    const queryBuilder = this.usersRepository.createQueryBuilder('user')
      .leftJoinAndSelect('user.userRoles', 'userRole')
      .leftJoinAndSelect('userRole.role', 'role');

    // 精确搜索条件
    if (username) {
      queryBuilder.andWhere('user.username = :username', { username });
    }

    if (email) {
      queryBuilder.andWhere('user.email = :email', { email });
    }

    if (phone) {
      queryBuilder.andWhere('user.phone = :phone', { phone });
    }

    if (status !== undefined) {
      queryBuilder.andWhere('user.status = :status', { status });
    }

    // 使用通用工具进行搜索和分页
    return PaginationUtil.searchAndPaginate(
      queryBuilder,
      query,
      'user',
      ['username', 'email', 'nickname'], // 关键词搜索字段
      ['createTime', 'updateTime', 'lastLoginAt'] // 允许的排序字段
    );
  }

  async findById(id: number): Promise<User> {
    const user = await this.usersRepository.findOne({
      where: { id },
      relations: ['userRoles', 'userRoles.role'],
    });
    
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    
    return user;
  }

  async findByUsername(username: string): Promise<User | undefined> {
    return this.usersRepository.findOne({ 
      where: { username },
      relations: ['userRoles', 'userRoles.role'],
    });
  }

  async findByEmail(email: string): Promise<User | undefined> {
    return this.usersRepository.findOne({ where: { email } });
  }

  async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
    const user = await this.findById(id);
    
    // 如果更新密码，需要进行哈希处理
    if (updateUserDto.password) {
      updateUserDto.password = await bcrypt.hash(updateUserDto.password, 12);
    }
    
    Object.assign(user, updateUserDto);
    return this.usersRepository.save(user);
  }

  async remove(id: number): Promise<void> {
    const user = await this.findById(id);
    await this.usersRepository.remove(user);
  }

  async updateLastLogin(id: number): Promise<void> {
    await this.usersRepository.update(id, {
      lastLoginAt: new Date(),
    });
  }

  async updateStatus(id: number, status: number): Promise<User> {
    await this.usersRepository.update(id, { status });
    return this.findById(id);
  }

  async assignRoles(userId: number, roleIds: number[]): Promise<void> {
    console.log(`Assigning roles to user ${userId}:`, roleIds);
    
    await this.userRoleRepository.delete({ userId });
    
    if (roleIds && roleIds.length > 0) {
      const userRoles = roleIds.map(roleId => 
        this.userRoleRepository.create({ userId, roleId })
      );
      
      await this.userRoleRepository.save(userRoles);
      console.log(`Successfully assigned ${userRoles.length} roles to user ${userId}`);
    } else {
      console.log(`No roles to assign to user ${userId}`);
    }
  }
}